//
//  ZKcityListViewController.m
//  zkCityList
//
//  Created by 帮友贷 on 16/3/1.
//  Copyright © 2016年 帮友贷. All rights reserved.
//

#import "ZKcityListViewController.h"
#import "ZKCity.h"
#import "ZKcityModle.h"
#import "ZKTheCollectionViewCell.h"
#import "ZKCollectionView.h"
#import "ZKcollectionCell.h"

#import <CoreLocation/CoreLocation.h>

#define PMWIDTH [UIScreen mainScreen].bounds.size.width
#define PMHEIGHT [UIScreen mainScreen].bounds.size.height

@interface ZKcityListViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,CLLocationManagerDelegate>
{
    ZKCollectionView * collectionView;
}

@property (strong, nonatomic) IBOutlet UITableView *zkCityTabel;
/** 城市数组 */
@property (nonatomic ,strong) NSArray * cityGroups;

/** 热门城市 */
@property (nonatomic ,strong) NSArray * hotCitys;

/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager  *locationManager;

/** 地理编码 */
@property (nonatomic, strong) CLGeocoder *geoC;

@end

@implementation ZKcityListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view = [[[NSBundle mainBundle] loadNibNamed:@"ZKcityListViewController" owner:nil options:nil] lastObject];
    }
    return self;
}

static NSString * const zkCollectionID = @"collectionCell";

- (CLLocationManager *)locationManager
{
    if (!_locationManager) {
        
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 100;
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        
        if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
        {
            [_locationManager requestWhenInUseAuthorization];
            
        }
    }
    return _locationManager;
}

- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 开始定位
    [self.locationManager startUpdatingLocation];
    
    [self setUpView];
    
    [self setUpCollection];
    
    [self setUpLocation];
}

-(void)setUpLocation
{

//    [self.locationManager startUpdatingLocation];

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    // 2.判断用户是否授权
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"等待用户授权");
    }else if (status == kCLAuthorizationStatusAuthorizedAlways ||
              status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        NSLog(@"授权成功");
        
        
        _locationManager.distanceFilter = 10;
        
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    }else
    {
        NSLog(@"授权失败");
    }
}
/**
 *
 */
-(void)setUpView{
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    self.zkCityTabel.delegate = self;
    self.zkCityTabel.dataSource = self;
    
    self.zkCityTabel.sectionIndexColor = [UIColor colorWithRed:18.0f/255.0f green:235.0f/255.0f blue:154.0f/255.0f alpha:1];
    self.zkCityTabel.sectionIndexBackgroundColor = [UIColor clearColor];
}

-(void)setUpCollection{
    collectionView = [ZKCollectionView theCollectionView];
    collectionView.theCollectionView.delegate = self;
    collectionView.theCollectionView.dataSource = self;
    
    [collectionView.theCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ZKTheCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:zkCollectionID];
    
    collectionView.theCollectionView.backgroundColor = [UIColor whiteColor];
    
    _hotCitys = @[@"北京",@"天津",@"上海",@"深圳",@"广州",@"重庆",@"武汉",@"青岛",@"济南"];
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    
    [self.locationManager stopUpdatingLocation];
    
    CLLocation *currLocation=[locations lastObject];
    
    NSLog(@"la---%f, lo---%f",currLocation.coordinate.latitude,currLocation.coordinate.longitude);
    double theLatitude = currLocation.coordinate.latitude;
    double theLongitude = currLocation.coordinate.longitude;
    
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:theLatitude longitude:theLongitude];
    
    [self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if(error == nil)
        {
            [placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSLog(@"%@", obj.locality);
//                self.addressTV.text = obj.name;
//                self.laTF.text = ;
                
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"当前位置" message:obj.locality delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                
                NSLog(@"%@",@(obj.location.coordinate.latitude).stringValue);
                NSLog(@"%@",@(obj.location.coordinate.longitude).stringValue);
                
            }];
        }else
        {
            NSLog(@"%@",error);
        }
        
    }];
}


-(NSArray *)cityGroups
{
    if (_cityGroups == nil) {
        _cityGroups = [ZKcityModle cityGroups];
    }
    
    return _cityGroups;
}

#pragma mark tableView delegate

// 分组总数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.cityGroups.count+2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section < 2) {
        return 1;
    } else {
        ZKcityModle * cityModel = self.cityGroups[section-2];
        
        return cityModel.citys.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 44;
    } else if (indexPath.section == 1) {
        return 120;
    } else {
        return 44;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString * ID = @"head";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.textLabel.text = @"北京市";
        return cell;
        
    } else if (indexPath.section == 1) {
        
        ZKcollectionCell * cell = [ZKcollectionCell theDetailViewCell:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        collectionView.frame = CGRectMake(0, 0, cell.cellBgView.frame.size.width, 120);
        
        collectionView.frame = cell.contentView.frame;
        [cell.cellBgView addSubview:collectionView];
        
//        NSLog(@"%@",collectionView);
//        [cell.contentView addSubview:collectionView];
        
        return cell;
        
    } else {
        static NSString * ID = @"cell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        // 设置cell内容
        // 1> 取出数据模型
        ZKcityModle *group = self.cityGroups[indexPath.section-2];
        ZKCity * city = group.citys[indexPath.row];
        
        cell.textLabel.text = city.city_name;
        
        return cell;
    }
}

// 标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"⭐️";
    } else if (section == 1) {
        return @"🔥";
    } else {
        // 找到group
        ZKcityModle *group = self.cityGroups[section-2];
        
        return group.titleName;
    }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    
    [arr addObject:@"⭐️"];
    [arr addObject:@"🔥"];
    [arr addObjectsFromArray:[self.cityGroups valueForKeyPath:@"titleName"]];
    
    return arr;
}

#pragma mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//多少行
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.hotCitys.count;
}

//每行显示什么（每行并不是一行，而是一个cell）
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *iden = @"pp";
    
    ZKTheCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:zkCollectionID forIndexPath:indexPath];
    
    
    cell.cityLabel.text = self.hotCitys[indexPath.row];
    
    return cell;
}
//
////点击
//-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    MyLogController *controller1=[[MyLogController alloc]init];
//    controller1.hidesBottomBarWhenPushed=YES;
//    
//    hongBaoViewController *controller2=[[hongBaoViewController alloc]init];
//    
//    controller2.hidesBottomBarWhenPushed=YES;
//    
//    MyInvestmentController *controller3=[[MyInvestmentController alloc]init];
//    controller3.myTouZi = @"wodetouzi";
//    controller3.hidesBottomBarWhenPushed=YES;
//    
//    MyPlanViewController *controller4=[[MyPlanViewController alloc]init];
//    controller4.hidesBottomBarWhenPushed=YES;
//    
//    myCreditor_rights *controller5=[[myCreditor_rights alloc]init];
//    controller5.hidesBottomBarWhenPushed=YES;
//    
//    WithCashController *controller7=[[WithCashController alloc]init];
//    controller7.hidesBottomBarWhenPushed=YES;
//    
//    agreementTableView *controller8=[[agreementTableView alloc]init];
//    controller8.hidesBottomBarWhenPushed = YES;
//    
//    AutomaticBidController * controller9 = [[AutomaticBidController alloc] init];
//    controller9.hidesBottomBarWhenPushed = YES;
//    //    controller9.zhanghuMoney = self.zhanghuMoney;
//    //    controller9.is_effect = self.is_effect;
//    
//    theLoanViewController * controller10 = [[theLoanViewController alloc] init];
//    
//    RepaymentController *controller11=[[RepaymentController alloc]init];
//    controller11.hidesBottomBarWhenPushed=YES;
//    
//    MyLoanInvestmentListController *controller12=[[MyLoanInvestmentListController alloc]init];
//    controller12.hidesBottomBarWhenPushed=YES;
//    
//    NSArray * arr = [[NSArray alloc]init];
//    arr = @[controller8,controller9,controller3,controller4,controller5,controller1,controller6,controller7,controller2,controller10,controller11,controller12];
//    
//    if (indexPath.row == 9) {
//        self.tabBarController.selectedIndex = 2;
//        
//    }else{
//        [self.navigationController pushViewController:arr[indexPath.row] animated:YES];
//        
//    }
//}
//
//设置每个cell大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(PMWIDTH/3-30, 26);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
//
////段头段尾
//-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    if(kind == UICollectionElementKindSectionHeader){
//        
//        
//        //段头
//        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
//        
//        UIButton * btn1 = (UIButton *)[header.view2 viewWithTag:4444];
//        [btn1 addTarget:self action:@selector(payIn:) forControlEvents:UIControlEventTouchUpInside];
//        
//        UIButton * btn2 = (UIButton *)[header.view2 viewWithTag:4445];
//        [btn2 addTarget:self action:@selector(payOut:) forControlEvents:UIControlEventTouchUpInside];
//        
//        UIButton * btn3 = (UIButton *)[header.view1 viewWithTag:4446];
//        [btn3 addTarget:self action:@selector(leftBtn:) forControlEvents:UIControlEventTouchUpInside];
//        
//        UIButton * btn4 = (UIButton *)[header.view1 viewWithTag:4447];
//        [btn4 addTarget:self action:@selector(rightBtn:) forControlEvents:UIControlEventTouchUpInside];
//        
//        return header;
//    }else{
//        return nil;
//    }
//}

@end
